/*
Package auth
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/3/26 18:06
@File     : auth.go
@Project  : gohub
@Desc     :
*/
package auth

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gohub/app/models/user"
	"gohub/pkg/logger"
)

// Attempt 尝试登录
func Attempt(email, password string) (user.User, error) {
	userModel := user.GetByMulti(email)
	if userModel.ID == 0 {
		return user.User{}, errors.New("账户不存在")
	}
	if !userModel.ComparePassword(password) {
		return user.User{}, errors.New("密码错误")
	}

	return userModel, nil
}

// LoginByPhone 登录指定用户
func LoginByPhone(phone string) (user.User, error) {
	userModel := user.GetByPhone(phone)
	if userModel.ID == 0 {
		return user.User{}, errors.New("账户不存在")
	}
	return userModel, nil
}

/**
 * CurrentUser
 * @Description: 从gin.context中获取当前当前登录用户
 * @param c
 * @return user.User
 */
func CurrentUser(c *gin.Context) user.User {
	userModel, ok := c.MustGet("current_user").(user.User)
	if !ok {
		logger.LogIf(errors.New("无法获取用户"))
		return user.User{}
	}
	return userModel
}
func CurrentUID(c *gin.Context) string {
	return c.GetString("current_user_id")
}
